#include <termios.h>
#include <unistd.h>
#include <string.h>
//#include <curses.h>
#include <stdio.h>
#include <memory.h>

#include "ConTLN.h"

#define DEBUG_OUT

static struct termios oterm;
static int fd = 0;

static char keyState[KEY_NUMBER];
#ifdef DEBUG_OUT
static char keyCode[KEY_NUMBER];
#endif

int StoreEnv()
{
  struct termios term;

  /* get the terminal settings */
  tcgetattr(fd, &oterm);

  /* get a copy of the settings, which we modify */
  memcpy(&term, &oterm, sizeof(term));

  /* put the terminal in non-canonical mode, any
     reads timeout after 0.1 seconds or when a
     single character is read */
  term.c_lflag = term.c_lflag & (!ICANON);
  term.c_cc[VMIN] = 0;
  term.c_cc[VTIME] = 1;

  //memset(keyState, 0, KEY_NUMBER*sizeof(KeyState));

  return (tcsetattr(fd, TCSANOW, &term) == 0);
}

int KB_UpdateStatus(char buffer[KEY_NUMBER])
{
  int achar;
  int i, updated=0;
  achar = getchar();

  memset(keyState, 0, KEY_NUMBER);
  if(achar!=-1)
  {
    ungetc(achar, stdin);
    updated = 1;

#ifdef DEBUG_OUT
    memset(keyCode, 0, KEY_NUMBER);
#endif
    for(i=0; (EOF != (achar = getchar())) && i<4; ++i )
    {
      keyState[achar] = 1;
      keyCode[i] = achar;
#ifdef DEBUG_OUT
      printf("%d,", achar);
#endif
    }

#ifdef DEBUG_OUT
    printf("%s\n", keyCode);
#endif
  }

  if(buffer)
  {
    memcpy(buffer, keyState, KEY_NUMBER);
  }
  return updated;
}

int KB_CheckKey(int key)
{
  return (keyState[key]);
}


void RestoreEnv()
{
  /* reset the terminal to original state */
  tcsetattr(fd, TCSANOW, &oterm);
}

